<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.7.10/dist/vue.js"></script>
</head>

<body>

  <!-- 
        事件总线：
            1) let bus = new Vue();  事件总线
                 bus.$on("eat",callback)  订阅  监听
                 bus.$emit("eat",'hello')  发布  可以传递数据
                 bus.$off("eat")  取消订阅  取消监听
                 bus.$once("eat")  只监听一次，或只订阅一次
     -->
  <div id="app">
    <h2>{{name}}</h2>
    <ml-wc></ml-wc>
    <hr>
    <ml-xq></ml-xq>
  </div>

  <script>
    let bus = new Vue();; // 事件总线

    // 目的是让wc和xq彼此通信？
    // wc: 订阅者   xq需要发布，发布时就可以传递数据
    // xq: 订阅者   wc需要发布，发布时就可以传递数据
    Vue.component("ml-wc", {
      template: `
                <div>
                    <h2>wc在线</h2>
                    <input type="text" v-model="msg" @keyup.enter="send" />
                    <button @click="send">发送</button>
                    <div v-html="content"></div>
                </div>
            `,
      data() {
        return {
          msg: "",
          content: ""
        }
      },
      mounted() {
        bus.$on("wc", msg => {
          console.log('wc收集到数据:', msg);
          this.content += `<div class='row'>xq说：${msg}</div>`
        })
      },
      methods: {
        send() {
          bus.$emit("xq", this.msg)
          this.msg = ""
        }
      },
    })
    Vue.component("ml-xq", {
      template: `
                <div>
                    <h2>xq在线</h2>
                    <input type="text" v-model="msg" @keyup.enter="send" />
                    <button @click="send">发送</button>
                    <div v-html="content"></div>
                </div>
            `,
      data() {
        return {
          msg: "",
          content: ""
        }
      },
      mounted() {
        bus.$on("xq", msg => {
          console.log('xq收集到数据:', msg);
          this.content += `<div class='row'>wc说：${msg}</div>`
        })
      },
      methods: {
        send() {
          bus.$emit("wc", this.msg)
          this.msg = "";
        }
      },
    })

    let vm = new Vue({
      el: "#app",
      data() {
        return {
          name: "码路",
        }
      }
    });
  </script>

</body>

</html>